<?php
/*
 * @Author: 莫莫
 * @Phone: 13450159681
 * @Description: 
 * @Date: 2024-10-22 17:06:17
 * @LastEditTime: 2025-01-08 20:41:46
 */

namespace app\index\controller;

class QyapiController extends Base
{


	private $token;
	private $encodingAesKey;
	private $appId;

	public function __construct($token = "3C5Wf5D9xqVP4W4wPxlYcb", $encodingAesKey = "T2JutcOniDmfWqeWK5UormJfus3pNRYmnDThxAk2xhz", $appId = "ww6b67187c8ed179a9")
	{
		$this->token = $token;
		$this->encodingAesKey = base64_decode($encodingAesKey . '=');
		$this->appId = $appId;
	}
	/**
	 * 回调地址
	 */
	public function callback()
	{
		// file_put_contents('wechat1.log', json_encode($_GET));
		$xml = $this->decryptMsg('motong');
		// return $this->json(['data' => $xml]);
		echo $xml;
	}

	public function decryptMsg($encryptMsg)
	{
		// 对密文进行解密
		$ciphertext_dec = base64_decode($encryptMsg);
		$iv = substr($this->encodingAesKey, 0, 16);
		$decrypted = openssl_decrypt($ciphertext_dec, 'AES-256-CBC', $this->encodingAesKey, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);

		// 去除补位字符
		$result = $this->decode($decrypted);

		// 去除16位随机字符串, 网络字节序
		if (strlen($result) < 16) {
			return "";
		}
		$content = substr($result, 16, strlen($result));
		$len_list = unpack("N", substr($content, 0, 4));
		$xml_len = $len_list[1];
		$xml_content = substr($content, 4, $xml_len);
		$from_appid = substr($content, $xml_len + 4);

		if ($from_appid != $this->appId) {
			return "";
		}
		return $xml_content;
	}

	private function decode($text)
	{
		$pad = ord(substr($text, -1));
		if ($pad < 1 || $pad > 32) {
			$pad = 0;
		}
		return substr($text, 0, (strlen($text) - $pad));
	}
}
